# Copyright (C) 2002-2003, 2010 The Written Word, Inc.
# Copyright (C) 2000-2001 The Written Word, LLC
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# $Id: file.py 728 2010-07-19 20:34:04Z china $

import os
import re
import sys
import types
import urllib2

from urlparse import urlparse

from depot import Depot
from misclib import urljoin

class file (Depot):
  def __init__ (self, var, dep, sub_depot):
    # This is better, but doesn't work for classic classes:
    #    super (file, self).__init__ (dep)
    # So, we're forced to hardcode the superclass for now:
    Depot.__init__ (self, dep)

    if type (dep) == types.InstanceType:
      url = dep.url
      self.var = dep.var
    else:
      url = dep
      self.var = var

    self.local_path = urlparse (url).path

    # add to existing depot path
    if type (dep) == types.InstanceType:
      self.local_path = os.path.join (dep.local_path, sub_depot)
      self.pkg_url = urljoin (dep.pkg_url, sub_depot)
    else:
      if var and var['dist'] and os.path.exists (os.path.join (self.local_path, var['dist'])):
        self.local_path = os.path.join (self.local_path, var['dist'])
        self.pkg_url = urljoin (self.pkg_url, var['dist'])

  # if file exists
  def exists (self, path = None):
    if path:
      return os.path.exists (os.path.join (self.local_path, path))
    else:
      return os.path.exists (self.local_path)

  def get (self, pkginst, show_progress = False):
    pass

  # if depot is on a remote server
  def is_remote (self):
    return False

  def local_uptodate (self, file):
    return True

  def open (self, path, mode):
    if self.archive:
      # depot is a zip archive
      return self.archive.open (path[len (self.archive.path) + 1:], mode)
    else:
      return open (os.path.join (self.local_path, path))

  # handle proxy and authentication
  def urlopen (self, url):
    return urllib2.urlopen (url)
